package fit.deni.hibernate;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import fit.deni.beans.DVD;
import fit.deni.beans.Zanr;
import fit.deni.hibernate.interfaces.DVDService;
public class DVDServiceImpl implements DVDService {

	private Session session;

	public DVDServiceImpl(Session session) {
		this.session = session;
	}

	@CommitAfter
	public void addDVD(DVD dvd) {
		session.merge(dvd);
	}
	
	@CommitAfter
	public void deleteDVD(DVD dvd) {
		dvd.setDeleted(true);
		session.merge(dvd);
//		session.delete(dvd);
//		session.flush();
	}
	
	public DVD getDVDById(int id) {
		return (DVD) session.createCriteria(DVD.class).add(Restrictions.eq("id", id)).list().get(0);
	}

	public Collection<DVD> getAll() {
		return session.createCriteria(DVD.class).add(Restrictions.eq("deleted", false)).list();
	}

	public Collection<DVD> getNewDVDs() {
		return session.createCriteria(DVD.class).add(Restrictions.eq("deleted", false)).addOrder(Order.desc("id")).list();
	}

	public Collection<DVD> getPopularDVDs() {
		return session.createCriteria(DVD.class).add(Restrictions.eq("deleted", false)).addOrder(Order.desc("putaIznajmljen")).list();
	}

	public DVD getDVDbyTitle(String title) {
		Collection<DVD> originals = session.createCriteria(DVD.class)
			.add(Restrictions.eq("deleted", false))
			.add(Restrictions.eq("originalniNaziv", title)).list();
		if(originals.size() > 1) {
			throw new RuntimeException("Too many results is returned");
		}
		if(originals.size() > 0) {
			return new LinkedList<DVD>(originals).get(0);
		}
		Collection<DVD> prevodi = session.createCriteria(DVD.class)
			.add(Restrictions.eq("deleted", false))
			.add(Restrictions.eq("prevod", title)).list();
		if(prevodi.size() > 1) {
			throw new RuntimeException("Too many results is returned");
		}
		if(prevodi.size() > 0) {
			return new LinkedList<DVD>(prevodi).get(0);
		}
		return null;
	}

	public Collection<DVD> getDVDByGenre(String genre) {
		Zanr zanr = (Zanr) session.createCriteria(Zanr.class)
			.add(Restrictions.eq("deleted", false))
			.add(Restrictions.eq("tip", genre)).list().get(0);
		Collection<DVD> all = getAll();
		Collection<DVD> result = new LinkedList<DVD>();
		for (DVD dvd : all) {
			if(dvd.getZanrovi().contains(zanr)) result.add(dvd);
		}
		return result;
	}
	
	public Collection<DVD> getDVDsFromActor(int glumacId) {
		Query query = session.createSQLQuery("SELECT * FROM DVD_evi d JOIN Glumci g ON d.id WHERE d.id = :glumac_id")
		.addEntity("DVD_evi", DVD.class)
		.setParameter("glumac_id", glumacId);
		return query.list();
	}

}
